package org.example.xsda.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.xsda.common.PageResult;
import org.example.xsda.entity.StudentRecord;
import org.example.xsda.exception.BusinessException;
import org.example.xsda.mapper.StudentRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 档案记录服务
 */
@Slf4j
@Service
public class RecordService {

    @Autowired
    private StudentRecordMapper studentRecordMapper;

    @Autowired
    private RedisService redisService;

    // 缓存key前缀
    private static final String CACHE_KEY_RECORD_BY_STUDENT = "record:student:";

    /**
     * 分页查询档案记录
     */
    public PageResult<StudentRecord> page(Long current, Long size, Long studentId, Integer recordType) {
        Page<StudentRecord> page = new Page<>(current, size);
        LambdaQueryWrapper<StudentRecord> wrapper = new LambdaQueryWrapper<>();
        
        if (studentId != null) {
            wrapper.eq(StudentRecord::getStudentId, studentId);
        }
        if (recordType != null) {
            wrapper.eq(StudentRecord::getRecordType, recordType);
        }
        wrapper.orderByDesc(StudentRecord::getCreateTime);
        
        Page<StudentRecord> recordPage = studentRecordMapper.selectPage(page, wrapper);
        return new PageResult<>(recordPage.getTotal(), recordPage.getRecords(), recordPage.getCurrent(), recordPage.getSize());
    }

    /**
     * 获取学生所有档案记录（带缓存）
     */
    @SuppressWarnings("unchecked")
    public List<StudentRecord> getByStudentId(Long studentId) {
        String cacheKey = CACHE_KEY_RECORD_BY_STUDENT + studentId;
        
        // 先从缓存中获取
        Object cached = redisService.get(cacheKey);
        if (cached != null) {
            log.debug("从缓存中获取学生档案记录：studentId={}", studentId);
            return (List<StudentRecord>) cached;
        }
        
        // 缓存未命中，从数据库查询
        LambdaQueryWrapper<StudentRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentRecord::getStudentId, studentId);
        wrapper.orderByDesc(StudentRecord::getCreateTime);
        List<StudentRecord> records = studentRecordMapper.selectList(wrapper);
        
        // 存入缓存（15分钟）
        redisService.set(cacheKey, records, 15, java.util.concurrent.TimeUnit.MINUTES);
        log.debug("将学生档案记录存入缓存：studentId={}", studentId);
        
        return records;
    }

    /**
     * 新增档案记录
     */
    public void add(StudentRecord record) {
        record.setCreateUser(StpUtil.getLoginIdAsLong());
        studentRecordMapper.insert(record);
        
        // 清除缓存
        clearRecordCache(record.getStudentId());
        
        log.info("新增档案记录成功：学生ID={}, 类型={}", record.getStudentId(), record.getRecordType());
    }

    /**
     * 更新档案记录
     */
    public void update(StudentRecord record) {
        StudentRecord existRecord = studentRecordMapper.selectById(record.getId());
        if (existRecord == null) {
            throw new BusinessException("档案记录不存在");
        }

        studentRecordMapper.updateById(record);
        
        // 清除缓存
        clearRecordCache(existRecord.getStudentId());
        
        log.info("更新档案记录成功：ID={}", record.getId());
    }

    /**
     * 删除档案记录
     */
    public void delete(Long id) {
        StudentRecord record = studentRecordMapper.selectById(id);
        if (record == null) {
            throw new BusinessException("档案记录不存在");
        }

        studentRecordMapper.deleteById(id);
        
        // 清除缓存
        clearRecordCache(record.getStudentId());
        
        log.info("删除档案记录成功：ID={}", id);
    }
    
    /**
     * 清除档案记录相关缓存
     */
    private void clearRecordCache(Long studentId) {
        // 清除学生档案记录缓存
        redisService.delete(CACHE_KEY_RECORD_BY_STUDENT + studentId);
        
        // 清除学生档案缓存（因为档案中包含最近档案记录）
        redisService.deleteByPattern("student:profile:");
        
        log.debug("清除档案记录缓存：studentId={}", studentId);
    }
}

